<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;

// 苹果支付相关
use App\Models\AppUsers;
use App\Models\Order;
use App\Models\Product;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Imdhemy\AppStore\ClientFactory;
use Imdhemy\AppStore\Receipts\Verifier;
use Imdhemy\AppStore\ValueObjects\LatestReceiptInfo;

//  失败后的队列处理

class PayController extends Controller
{


    /**
     * 新版苹果内购支付
     * @param $receipt  内购后返回的base64的加密字符串 前端拿到给后端即可
     * @param $user
     */
    public function applePurchase()
    {
        $receipt = request()->post('receipt');
//        Log::info('receipt-data', [
//            'data' => request()->all()
//        ]);
        $client = ClientFactory::create();

        $verifier = new Verifier($client, $receipt, env('APPLE_PAY_PASSWORD'));   // 需要共享密码 详看文档

        try {
            $receiptResponse = $verifier->verify();
        } catch (\Exception $e) {
            return false;
        }
        // 获取验证的状态
        $status = $receiptResponse->getStatus();
        // 验证通过 开始处理
        if ($status->isValid()) {
            // 获取环境
            $environment    = $receiptResponse->getEnvironment();
            $receiptInfoArr = $receiptResponse->getReceipt()->getInApp();
            // 存在即可进行处理
            if (count($receiptInfoArr)) {
                try {
                    DB::transaction(function () use ($receiptInfoArr, $environment) {
                        $receiptInfoCollection = new Collection();
                        foreach ($receiptInfoArr as $receiptObj) {
                            $receiptInfo = self::getAppleOrderInfo($receiptObj, $environment);
                            $receiptInfoCollection->push($receiptInfo);
                        }
                        if ($receiptInfoCollection->isNotEmpty()) {
                            $receiptInfoCollection = $receiptInfoCollection->sortBy(function ($item) {
                                return $item['purchase_date'];
                            });
                            $receiptInfoCollection->each(function ($receiptInfo) {
                                // 购买成功之后做逻辑
                                // 需要检测苹果返回的订单号加上用户数据存在不 不存在 进行相关处理
                                $order = Order::where(['number' => $receiptInfo['transaction_id']])->first();
                                $token = request()->post('token', '');
                                $uuid  = request()->post('uuid', '');
                                $user  = AppUsers::with(['level'])->where('api_token', $token)->where('uuid', $uuid)->first();
                                if ($order) {
                                    if (request()->post('recovery', '') == true) {
                                        $order->admin_id = $user->id;
                                        $order->save();
                                    } else {
                                        return;
                                    }
                                }
                                $product = Product::with(['level'])->where(['apple_id' => $receiptInfo['product_id']])->first();
                                if (Carbon::now()->diffInMinutes($user->expires, false) <= 0 || empty($user->level)) {
                                    $user->start_time = Carbon::now()->toDateTimeString();
                                    $user->expires    = Carbon::now()->addMinutes($product->minute)->toDateTimeString();
                                } else if ($product->level->weight > $user->level->weight) {
                                    $user->expires = Carbon::parse($user->start_time)->addMinutes($product->minute)->toDateTimeString();
                                } else if ($product->level->weight < $user->level->weight) {
                                    $user->expires = Carbon::parse($user->start_time)->addMinutes($product->minute)->toDateTimeString();
                                }
                                $user->level_id = $product->level_id;
                                $user->save();

                                if (!$order) {
                                    $order = new Order([
                                        'number'     => $receiptInfo['transaction_id'],
                                        'total'      => $product->price,
                                        'product_id' => $product->id,
                                        'is_pay'     => true,
                                        'admin_id'   => $user->id,
                                        'payment'    => 'ios',
                                        'pay_time'   => $receiptInfo['purchase_date']
                                    ]);
                                    $order->save();
                                }
                            });

                        }
                    }, 5);
                } catch (\Exception | \Throwable $ex) {
                    return $this->errors(-1, '支付失败');
                }
                return $this->success(200, '成功');
            }
        }
        return $this->errors(-1, '支付失败');
    }

    /**
     * 返回苹果内购的信息
     * @param LatestReceiptInfo $receiptInfo
     * @param string $environment 环境
     * @return array
     */
    protected static function getAppleOrderInfo(LatestReceiptInfo $receiptInfo, $environment = 'Sandbox'): array
    {
        return [
            'environment'    => $environment, // 环境
            'product_id'     => $receiptInfo->getProductId(), // 产品ID
            'transaction_id' => $receiptInfo->getTransactionId(), // 苹果订单号
            'purchase_date'  => $receiptInfo->getPurchaseDate() ? $receiptInfo->getPurchaseDate()->getCarbon()->format('Y-m-d H:i:s') : null, // 购买时间
            'expires_date'   => $receiptInfo->getExpiresDate() ? $receiptInfo->getExpiresDate()->getCarbon()->format('Y-m-d H:i:s') : null, // 过期时间
        ];
    }

    public function recovery()
    {
        $receipt = request()->post('receipt');
        $client  = ClientFactory::create();

        $verifier = new Verifier($client, $receipt, env('APPLE_PAY_PASSWORD'));   // 需要共享密码 详看文档

        try {
            $receiptResponse = $verifier->verify();
        } catch (\Exception $e) {
            return false;
        }
        // 获取验证的状态
        $status = $receiptResponse->getStatus();
        // 验证通过 开始处理
        if ($status->isValid()) {
            // 获取环境
            $environment    = $receiptResponse->getEnvironment();
            $receiptInfoArr = $receiptResponse->getReceipt()->getInApp();
            // 存在即可进行处理
            if (count($receiptInfoArr)) {
                foreach ($receiptInfoArr as $receiptObj) {
                    $receiptInfo = self::getAppleOrderInfo($receiptObj, $environment);
                    try {
                        \DB::beginTransaction();
                        // 购买成功之后做逻辑
                        // 需要检测苹果返回的订单号加上用户数据存在不 不存在 进行相关处理
                        $order = Order::where(['number' => $receiptInfo['transaction_id']])->first();
                        $token = request()->post('token', '');
                        $uuid  = request()->post('uuid', '');
                        $user  = AppUsers::with(['level'])->where('api_token', $token)->where('uuid', $uuid)->first();
                        if (empty($order)) {
                            continue;
                        }
                        $order->admin_id = $user->id;
                        $order->save();
                        $product = Product::with(['level'])->where(['id' => $order->product_id])->first();
                        if (Carbon::now()->diffInMinutes($user->expires, false) <= 0 || empty($user->level)) {
                            $user->start_time = Carbon::now()->toDateTimeString();
                            $user->expires    = Carbon::now()->addMinutes($product->minute)->toDateTimeString();
                        } else if ($product->level->weight > $user->level->weight) {
                            $user->expires = Carbon::parse($user->start_time)->addMinutes($product->minute)->toDateTimeString();
                        } else if ($product->level->weight < $user->level->weight) {
                            $user->expires = Carbon::parse($user->start_time)->addMinutes($product->minute)->toDateTimeString();
                        }
                        $user->level_id = $product->level_id;
                        $user->save();
                        \DB::commit();
                    } catch (\Exception $ex) {
                        // 回滚
                        \DB::rollBack();
                        // 记录异常
//                        Log::Error();
//                        // 加入队列重试处理
//                        ApplePayFailJob::dispatch();
                        continue;
                    }
                }
                return $this->success(200, '成功');
            }
        }
        return $this->errors(-1, '支付失败');
    }
}
